package com.example.cinema.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.databinding.library.baseAdapters.BR;

import com.example.cinema.R;
import com.example.cinema.RequestAuthority;
import com.example.cinema.UserAttribute;
import com.example.cinema.adapter.TypeGridAdapter;
import com.example.cinema.adapter.UnifiedWorksAdapter;
import com.example.cinema.bindingdata.UpFileInfoData;
import com.example.cinema.bindingdata.UserWorksData;
import com.example.cinema.databinding.ActivityUserworksBinding;
import com.example.cinema.drawview.ShortPlayerVideo;
import com.example.cinema.request.OkhttpBlock;
import com.example.cinema.request.ProgressResponseListener;
import com.example.cinema.request.RequestData;
import com.example.cinema.testdara.TestData;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

public class ActivityUserWorks extends AppCompatActivity {

    @Override
    protected void onResume() {
        super.onResume();
        if(playerVideo!=null)
        {
            playerVideo.Playstart();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(playerVideo!=null)
        {
            playerVideo.Playstop();
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        if(playerVideo!=null)
        {
            playerVideo.Playstop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(playerVideo!=null)
        {
            playerVideo.Playrelease();
        }
    }

    private long filesize = 0;
    private File upfile = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAGS && data != null) {
            //取绝对路径
            filesize = 0;
            upfile = null;
            Uri uri = data.getData();
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            String vpath = cursor.getString(1);
            String vsize = cursor.getColumnName(2);
            String vname = cursor.getColumnName(3);
            Log.i("HHH", vpath + "");
            Log.i("HHH", vsize + "");
            Log.i("HHH", vname + "");
            upfile = new File(vpath);
            if (!upfile.exists()) {
                Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
                return;
            }

            try {
                FileInputStream stream = new FileInputStream(upfile);
                filesize = stream.getChannel().size();
                String name = upfile.getName();
                Log.i("HHH", filesize + "");
                Log.i("HHH", name + "");
                int i = name.indexOf(".mp4");
                if(i<0)
                {
                    return;
                }

                if (filesize > RequestAuthority.filemaxsize) {
                    Toast.makeText(this, "文件多大无法上传", Toast.LENGTH_LONG).show();
                    stream.close();
                    return;
                }

                VideoInfo();

                stream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Toast.makeText(this, data.getData() + "", Toast.LENGTH_LONG).show();
        }
    }

    //打开视频信息补充
    private AlertDialog alertDialog;

    private void VideoInfo() {
        int width = getResources().getDisplayMetrics().widthPixels;

        ViewDataBinding view = DataBindingUtil.inflate(LayoutInflater.from(getApplicationContext()),
                R.layout.upfile_info, null, false);

        UpFileInfoData infoData = new UpFileInfoData();
        view.setVariable(BR.infodata, infoData);
        alertDialog = new AlertDialog.Builder(this)
                .setView(view.getRoot())
                .create();
        alertDialog.setCancelable(false);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);

        window.getDecorView().setBackgroundColor(Color.parseColor("#00000000"));

        WindowManager.LayoutParams params = window.getAttributes();
        params.width = width;
        params.height = 1100;
        window.setAttributes(params);
        view.getRoot().findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("LLL", "确定上传");
                Log.i("LLL", infoData.videoname.get() + "确定上传");
                if (infoData.videoinfo.get() == null || infoData.videoname.get() == null || infoData.videotags.get() == null) {
                    Toast.makeText(getApplicationContext(), "视频信息不全无法上传", Toast.LENGTH_LONG).show();
                    return;
                }
                alertDialog.cancel();
                ProgressView();
                upvideo(infoData.videoname.get(), infoData.videoinfo.get(), infoData.videotags.get());
            }
        });
    }

    //打开进度显示
    private AlertDialog progressDialog;
    private  SeekBar seekBar;

    public void ProgressView()
    {

        seekBar = new SeekBar(getApplicationContext());
        seekBar.setMax((int) (filesize/1000));
        seekBar.setThumb(null);
        seekBar.setSplitTrack(false);

        seekBar.setProgressDrawable(getResources().getDrawable(R.drawable.progress_seekbar_bag));

        progressDialog = new AlertDialog.Builder(this)
                .setView(seekBar)
                .create();
        progressDialog.setCancelable(false);
        progressDialog.show();

        seekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        Window window = progressDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setBackgroundColor(Color.parseColor("#00000000"));

    }


    //启动上传
    private long current = 0;
    public void upvideo(String name,String centent,String videotag)
    {
        current = 0;
        OkhttpBlock okhttpBlock = new OkhttpBlock();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Random random = new Random();
                int id = random.nextInt(200000)+100000;
                int csize = (int) (filesize / (1024 * 1024 * 2));
                Log.i("KKK","分块数"+csize);
                if (filesize % (1024 * 1024 * 2) > 0) {
                    csize++;
                }
                if(csize<1)
                {
                    csize = 1;
                }
                Log.i("JJJ",csize+"");
                for (int i=0;i<csize;i++)
                {
                    try {
                        okhttpBlock.upfile(upfile, filesize, String.valueOf(id), upfile.getName(),
                                String.valueOf(csize),String.valueOf(i+1),name,centent,videotag,
                                attribute.getUID(),attribute.getUname(),URL);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        //上传进度
        okhttpBlock.setOnProgressListener(new OkhttpBlock.ProgressListener() {
            @Override
            public void Progress(long byteCount) {
                Log.i("TTTSD",""+current);
                current+=byteCount;
                seekBar.setProgress((int) (current/1000));
                if(current>=filesize)
                {
                    progressDialog.cancel();
                }
            }
        });
    }



    private ActivityUserworksBinding AUS;
    private String URL;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AUS = DataBindingUtil.setContentView(this, R.layout.activity_userworks);
        attribute = (UserAttribute) getApplication();
        if(attribute.getUID()==null||attribute.getToken()==null)
        {
            Intent intent = new Intent();
            intent.setAction("sign");
            startActivity(intent);
            return;
        }
        ApplicationInfo info = null;
        try {
            info = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        URL = info.metaData.getString("url");
        init();
        initlistener();
        ThreadData();

        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = getWindow().getDecorView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }
    private UserAttribute attribute;
    private UnifiedWorksAdapter adapter;
    private  List<UserWorksData> list = new ArrayList<>();
    private void init() {
        adapter = new UnifiedWorksAdapter(list,R.layout.user_works_item, BR.userworks,getApplicationContext());

        AUS.gridview.setAdapter(adapter);
    }

    private void initlistener() {
        //返回
        AUS.finsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        if(attribute.getAppVideoUpMode()==1)
        {
            AUS.upfile.setVisibility(View.INVISIBLE);

        }else {
            //上传
            AUS.upfile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openvideo();
                }
            });
        }


        //滚动
        AUS.gridview.setOnScrollListener(new AbsListView.OnScrollListener() {
            private boolean sclstate = true;
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(scrollState==0)
                {
                    if(sclstate)
                    {
                        sclstate = false;
                        page++;
                        Toast.makeText(getApplicationContext(),"xxxxxx",Toast.LENGTH_LONG).show();
                        AddDilog();
                        ThreadData();
                    }

                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int t = firstVisibleItem + visibleItemCount;
                if(t>=totalItemCount)
                {
                    sclstate = true;
                }
            }
        });
        //点击
        AUS.gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String ss =list.get(position).fileurls.get();
                if(ss==null)
                {
                    Toast.makeText(getApplicationContext(),"播放地址找不到了",Toast.LENGTH_SHORT).show();
                    return;
                }
                String pl = list.get(position).fileimage.get();

                playershow(ss,pl);
            }
        });
    }
    //弹出播放
    private AlertDialog playdialog;
    private ShortPlayerVideo playerVideo;
    private void playershow(String url,String img)
    {
        int w = getResources().getDisplayMetrics().widthPixels;
        int h = getResources().getDisplayMetrics().heightPixels;

        playerVideo= new ShortPlayerVideo(getApplicationContext());
        LinearLayout.LayoutParams paramss = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        paramss.width = w;
        paramss.height= h;
        playerVideo.setLayoutParams(paramss);

        playdialog = new AlertDialog.Builder(ActivityUserWorks.this)
                .setView(playerVideo).show();
        Window window = playdialog.getWindow();
        window.getDecorView().setBackgroundColor(Color.argb(0,0,0,0));
        window.getDecorView().setPadding(0,0,0,0);
        WindowManager.LayoutParams params = window.getAttributes();
        params.height = h;
        params.width  = w;
        window.setAttributes(params);

        playerVideo.setImgUrl(img);
        playerVideo.setPlayurl(url);
        playerVideo.loadVideo();

        playdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                playerVideo.Playrelease();
            }
        });

    }

    //弹出缓冲动画
    private AlertDialog logingDialog;
    private float val = 360;
    private void AddDilog()
    {
        ImageView bufferdialog = new ImageView(getApplicationContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50,50);
        bufferdialog.setLayoutParams(params);
        bufferdialog.setImageDrawable(getResources().getDrawable(R.mipmap.ch));
        logingDialog = new AlertDialog.Builder(ActivityUserWorks.this)
                .setCancelable(false)
                .setView(bufferdialog).show();


        Window window = logingDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setBackgroundColor(Color.argb(0,0,0,0));

        XhAnimator(bufferdialog);
    }
    //循环动画
    private ValueAnimator animator;
    private void XhAnimator(View view)
    {
        animator = ValueAnimator.ofFloat(val);
        animator.setDuration(2000);
        animator.setInterpolator(new LinearInterpolator());
        animator.reverse();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float v = (float) animation.getAnimatedValue();
                view.setRotation(v);
                if(v==val)
                {
                    XhAnimator(view);
                }
            }
        });
        animator.start();

    }

    //打开视频列表
    private static final int TAGS = 0;
    private void openvideo()
    {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,"video/mp4");
        startActivityForResult(intent,TAGS);
    }

    //开启网络获取数据
    private int page = 1;
    private int limit= 30;
    private void ThreadData()
    {
        new Thread()
        {
            @Override
            public void run() {

                RequestData requestData = new RequestData(getApplicationContext());
                List<UserWorksData> ud = requestData.GetUserWorks(page,limit,attribute);
                list.addAll(ud);
                Message message = new Message();
                message.obj = ud;
                message.what= 1000;
                handler.sendMessage(message);
            }
        }.start();
    }

    Handler handler = new Handler(Looper.getMainLooper())
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == 1000)
            {
                if(page>1)
                {
                    animator.cancel();
                    logingDialog.cancel();
                }
                adapter.notifyDataSetChanged();
                return;
            }

        }
    };
}
